package main

import (
	"fmt"
	"net/http"
	"text/template"
)

type UserInfo struct {
	Name string
	Age  int
	Sex  string
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	// 1. 解析指定文件生成模板对象
	// 自定义一个函数, 必须在注册模板之前告诉模板引擎
	kua := func(name string) (string, error) {
		return name + "年轻又帅气多金!", nil
	}
	tmpl := template.New("hello.tmpl")
	tmpl.Funcs(template.FuncMap{
		"kua": kua,
	})
	_, err := tmpl.ParseFiles("./hello.tmpl", "./ul.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	// 2. 利用给定数据渲染模板，并将结果写入w
	user := UserInfo{
		Name: "沙河小王子",
		Age:  18,
		Sex:  "男",
	}

	m1 := map[string]interface{}{
		"name": "娜扎",
		"age":  18,
		"sex":  "女",
	}

	rangeList := [...]string{"篮球", "足球", "乒乓球"}

	// 3. 渲染模板
	tmpl.Execute(w, map[string]interface{}{
		"user": user,
		"m1":   m1,
		"list": rangeList,
	})
}

func sayBlock(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseGlob("./*.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	err = tmpl.ExecuteTemplate(w, "index.tmpl", nil)
	if err != nil {
		fmt.Println("render template failed, err:", err)
		return
	}
}

func main() {
	http.HandleFunc("/", sayHello)
	http.HandleFunc("/block", sayBlock)
	err := http.ListenAndServe(":9000", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}
